﻿import axios from 'axios'
import {Message} from 'element-ui'

const BASE_URL = "http://127.0.0.1:8000"
// const BASE_URL = "http://api.siuper.cn"
// const BASE_URL = "http://124.223.225.90:9000"
// create an axios instance
const service = axios.create({
    baseURL: BASE_URL, // url = base url + request url
    // withCredentials: true, // send cookies when cross-domain requests
    timeout: 5000 // request timeout
})

// request interceptor
service.interceptors.request.use(
        config => {
            // do something before request is sent

            config.data = {
                ...config.data,
                token: ""
            }
            if (config.isForm) {
                config.headers = {
                    ...config.headers,
                    "Content-Type": "multipart/form-data"
                }
            }

            return config
        },
        error => {
            console.log(error) // for debug
            return Promise.reject(error)
        }
)

// response interceptor
service.interceptors.response.use(
        response => {
            const res = response.data
            console.log(res)
            // if the custom code is not 20000, it is judged as an error.
            if (res.code !== 0) {
                Message({
                    message: res.msg,
                    type: 'error',
                    duration: 3 * 1000
                })
                if (res.code === 102) {
                    window.location.href = "/login";
                }
                return Promise.reject(new Error(res.msg || 'Error'))
            } else {
                return res
            }
        },
        error => {
            console.log('err' + error) // for debug
            return Promise.reject(error)
        }
)

export default service
